<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="50%"
             :close-on-click-modal="false" :close-on-press-escape="false"
             destroy-on-close @close="closeDialog">
    <el-form :model="formData" ref="form" label-width="100px" :inline="true" :disabled="disabled">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商品分类" prop="commodityClassify" :rules="[validator.required]">
            <el-select v-model="formData.commodityClassify" placeholder="请选择活动区域">
              <el-option
                v-for="dict in commodityClassifyOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称" prop="commodityName" :rules="[validator.required]">
            <el-input v-model="formData.commodityName"></el-input>
          </el-form-item>
          <el-form-item label="商品编码" prop="commodityCoding" :rules="[validator.required]">
            <el-input v-model="formData.commodityCoding"></el-input>
          </el-form-item>
          <el-form-item label="计量单位" prop="measureUnit" :rules="[validator.required]">
            <el-select v-model="formData.measureUnit" placeholder="请选择计量单位">
              <el-option
                v-for="dict in measureUnitOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark" :rules="[validator.required]">
            <el-input v-model="formData.remark"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规格" prop="specification" :rules="[validator.required]">
            <el-input v-model="formData.specification"></el-input>
          </el-form-item>
          <el-form-item label="单价" prop="unitPrice" :rules="[validator.required]">
            <el-input v-model="formData.unitPrice"></el-input>
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName" :rules="[validator.required]">
            <el-input v-model="formData.supplierName"></el-input>
          </el-form-item>
          <el-form-item label="销控区域" prop="pinControl" :rules="[validator.required]">
            <el-select v-model="formData.pinControl" multiple placeholder="请选择销控区域">
              <el-option
                v-for="dict in pinControlOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="品牌商标" v-if="type === 'add'">
        <el-upload
          class="upload"
          :action="action"
          :auto-upload="false"
          :on-preview="handlePreview"
          :on-success="handleUpload"
          :on-change="fileChange"
          list-type="picture"
          ref="upload"
          :file-list="fileList"
          :headers="myHeaders"
        :limit="1">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">限制上传一个，只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="品牌商标" v-if="type === 'update'">
        <p>原图 需要修改请重新上传</p>
        <img class="tablePic" @click="picPreview(GLOBAL.MAIN_SERVER +  formData.commodityLogo)" :src="GLOBAL.MAIN_SERVER +  formData.commodityLogo" alt="">
        <el-upload
          class="upload"
          :action="action"
          :auto-upload="false"
          :on-preview="handlePreview"
          :on-success="handleUpload"
          :on-change="fileChange"
          list-type="picture"
          ref="upload"
          :file-list="fileList"
          :headers="myHeaders"
          :limit="1">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">限制上传一个，只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="品牌商标" v-if="type === 'view'">
        <img class="tablePic" @click="picPreview(GLOBAL.MAIN_SERVER +  formData.commodityLogo)" :src="GLOBAL.MAIN_SERVER +  formData.commodityLogo" alt="">
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="picDialogVisible" append-to-body destroy-on-close>
      <img width="100%" :src="picDialogImageUrl" alt="">
    </el-dialog>
    <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">关闭</el-button>
    <el-button type="primary" @click="addCommodity" v-if="type === 'add'">新增</el-button>
    <el-button type="primary" @click="updateCommodity" v-if="type === 'update'">保存</el-button>
  </span>
  </el-dialog>
</template>

<script>
  import { saveCommodity } from '@/api/commodity-editor/commodity'
  import validator from '@/utils/validateList'
  import GLOBAL from '@/config/config';
  import { getToken } from '@/utils/auth'

  export default {
    name: 'editor',
    data() {
      return {
        dialogVisible: false,
        title: '',
        formData: {},
        type: '',
        disabled: false,
        validator: validator,
        GLOBAL: GLOBAL,
        commodityClassifyOptions: [],
        pinControlOptions: [],
        measureUnitOptions: [],
        action: '',
        fileList: [],
        myHeaders: {Authorization: ''},
        picDialogImageUrl: '',
        picDialogVisible: false
      }
    },
    methods: {
      openEditor(type, data) {
        this.type = type;
        this.dialogVisible = true;
        switch (type) {
          case 'add':
            this.title = '添加商品';
            break;
          case 'update':
            this.title = '修改商品';
            break;
          case 'view':
            this.title = '查看商品';
            this.disabled = true;
            break;
        }
        if (data) {
          this.formData = JSON.parse(JSON.stringify(data));
          this.formData.pinControl = this.formData.pinControl.split(',');
        }
        this.getDicts('fo_commodity_type').then(response => {
          this.commodityClassifyOptions = response.data;
        })
        this.getDicts('fo_control_area').then(response => {
          this.pinControlOptions = response.data;
        })
        this.getDicts('fo_measure_unit').then(response => {
          this.measureUnitOptions = response.data;
        })
        this.action = this.GLOBAL.MAIN_SERVER + '/common/upload';
        if ( getToken()) {
          this.myHeaders.Authorization = 'Bearer ' + getToken();
        }
      },
      addCommodity() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            //上传
            if (this.fileList.length > 0) {
              this.$refs.upload.submit();
            } else {
              this.$notify({
                title: '警告',
                message: `请上传一个品牌商标`,
                type: 'warning'
              })
            }
          }
        })
      },
      updateCommodity() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.fileList.length > 0) {
              this.$refs.upload.submit();
            } else {
              //成功再上传
              this.formData.pinControl = this.formData.pinControl.toString();
              saveCommodity(this.formData).then(response => {
                this.$notify({
                  title: '成功',
                  message: `${response.msg}`,
                  type: 'success'
                })
                this.dialogVisible = false;
                this.$emit('resetQuery')
              })
            }
          }
        })
      },
      closeDialog() {
        this.disabled = false;
        this.formData = {};
        this.myHeaders.Authorization = '';
        this.fileList = [];
        this.dialogVisible = false;
        this.$emit('resetQuery')
      },
      handlePreview(file) {
        this.picDialogImageUrl = file.url;
        this.picDialogVisible = true;
      },
      picPreview(url) {
        this.picDialogImageUrl = url;
        this.picDialogVisible = true;
      },
      fileChange(file, fileList) {
        console.log(file)
        console.log(fileList)
        this.fileList = fileList;
      },
      handleUpload(response) {
        if (response.msg === '操作成功') {
          this.formData.commodityLogo = response.fileName;
          //成功再上传
          this.formData.pinControl = this.formData.pinControl.toString();
          saveCommodity(this.formData).then(response => {
            this.$notify({
              title: '成功',
              message: `${response.msg}`,
              type: 'success'
            })
            this.dialogVisible = false;
            this.$emit('resetQuery');
          })
        } else {
          this.$notify({
            title: '失败',
            message: `图片上传失败！`,
            type: 'error'
          });
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  .el-form-item {
    width: 100%;

    .el-select {
      width: 100%;
    }

    /deep/ .el-form-item__content {
      width: calc(100% - 100px);
    }
  }
  .tablePic{
    max-height: 50px;
  }

</style>
